<?php
// ------------------------------------------------------------------------
// |@Author       : Jarmin <edshop@qq.com>
// |@----------------------------------------------------------------------
// |@Date         : 2023-01-17 21:41:25
// |@----------------------------------------------------------------------
// |@LastEditTime : 2023-01-31 16:33:20
// |@----------------------------------------------------------------------
// |@LastEditors  : Jarmin <jarmin@ladmin.cn>
// |@----------------------------------------------------------------------
// |@Description  : 
// |@----------------------------------------------------------------------
// |@FilePath     : Login.php
// |@----------------------------------------------------------------------
// |@Copyright (c) 2023 http://www.ladmin.cn   All rights reserved. 
// ------------------------------------------------------------------------
namespace app\admin\controller;

use think\admin\Controller;
use think\admin\extend\CodeExtend;
use think\admin\model\SystemUser;
use think\admin\service\AdminService;
use think\admin\service\CaptchaService;
use think\admin\service\RuntimeService;
use think\admin\service\SystemService;

/**
 * 用户登录管理
 * Class Login
 * @package app\admin\controller
 */
class Login extends Controller
{
    /**
     * 后台登录入口
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if ($this->app->request->isGet()) {
            if (AdminService::isLogin()) {
                $this->redirect(sysuri('admin/index/index'));
            } else {
                // 当前运行模式
                $this->developMode = RuntimeService::check();
                // 后台背景处理
                $images = str2arr(sysconf('login_image') ?: '', '|');
                if (empty($images)) $images = [
                    SystemService::uri('/static/theme/img/auth_banner.jpg'),
                    SystemService::uri('/static/theme/img/auth_banner.jpg'),
                ];
                $this->loginStyle = sprintf('style="background-image:url(%s)" data-bg-transition="%s"', $images[0], join(',', $images));
                // 登录验证令牌
                $this->captchaType = 'LoginCaptcha';
                $this->captchaToken = CodeExtend::uniqidDate(18);
                if (!$this->app->session->get('LoginInputSessionError')) {
                    $this->app->session->set($this->captchaType, $this->captchaToken);
                }
                // 更新后台域名
                if ($this->request->domain(true) !== sysconf('base.site_host')) {
                    sysconf('base.site_host', $this->request->domain(true));
                }
                // 加载登录模板
                $this->title = lang('login.title');
                $this->fetch();
            }
        } else {
            if ($this->app->request->get('type') === 'account') {
                $data = $this->_vali([
                    'username.require' => lang('login.userRequireError'),
                    'username.min:4'   => lang('login.userLengthError'),
                    'password.require' => lang('login.PWRequireError'),
                    'password.min:4'   => lang('login.PWLengthError'),
                    'verify.require'   => lang('login.verifRequireError'),
                    'uniqid.require'   => lang('login.uniqidRequireError'),
                ]);
                if (!CaptchaService::instance()->check($data['verify'], $data['uniqid'])) {
                    $this->error(lang('login.verifCheckError'));
                }
                /*! 用户信息验证 */
                $map = ['username' => $data['username'], 'is_deleted' => 0];
                $user = SystemUser::mk()->where($map)->findOrEmpty();
                if ($user->isEmpty()) {
                    $this->app->session->set('LoginInputSessionError', true);
                    $this->error(lang('login.userCheckError'));
                }
                if (empty($user['status'])) {
                    $this->app->session->set('LoginInputSessionError', true);
                    $this->error(lang('login.userStatusError'));
                }
                if (md5("{$user['password']}{$data['uniqid']}") !== $data['password']) {
                    $this->app->session->set('LoginInputSessionError', true);
                    $this->error(lang('login.PWCheckError'));
                }
                $user->hidden(['sort', 'status', 'password', 'is_deleted']);
                $this->app->session->set('user', $user->toArray());
                $this->app->session->delete('LoginInputSessionError');
                $user->inc('login_num')->update([
                    'login_at' => date('Y-m-d H:i:s'),
                    'login_ip' => $this->app->request->ip(),
                ]);
            } elseif ($this->app->request->get('type') === 'phone') {
                //
            } else {
                return false;
            }
            // 刷新用户权限
            AdminService::apply(true);
            sysoplog(lang('login.userLoginTitle'), lang('login.userLoginSuccess'));
            $this->success(lang('login.signInSuccess'), sysuri('admin/index/index'));
        }
    }

    /**
     * 生成验证码
     * @return void
     */
    public function captcha()
    {
        $input = $this->_vali([
            'type.require'  => lang('captcha.typeRequireErr'),
            'token.require' => lang('captcha.tokenRequireErr'),
        ]);
        $image = CaptchaService::instance()->initialize();
        $captcha = ['image' => $image->getData(), 'uniqid' => $image->getUniqid()];
        if ($this->app->session->get($input['type']) === $input['token']) {
            $captcha['code'] = $image->getCode();
            $this->app->session->delete($input['type']);
        }
        $this->success(lang('captcha.createSuccess'), $captcha);
    }

    /**
     * 退出登录
     * @return void
     */
    public function out()
    {
        $this->app->session->destroy();
        $this->success(lang('login.outLoginSuccess'), sysuri('admin/login/index'));
    }

    /**
     * 多语言设置
     */
    public function lang()
    {
        $lang = $this->app->request->get('lang');
        switch ($lang) {
            case 'en-us':
                $this->app->cookie->set('lang', 'en-us');
                break;
            case 'zh-cn':
                $this->app->cookie->set('lang', 'zh-cn');
                break;
            default:
                $this->app->cookie->set('lang','zh-cn');
                break;
        };
        $this->success(lang('login.langChangeSuccess'));
    }
}